package org.hgvc.webapp.ets.spring.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.myfaces.custom.fileupload.UploadedFile;
import org.hgvc.webapp.ets.constant.CommonConstant;
import org.hgvc.webapp.ets.exception.FileServiceException;
import org.jocsb.base.exception.BaseException;
import org.jocsb.base.filestream.StreamView;
import org.jocsb.base.util.SpringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.RedirectView;


public class FileServiceImpl implements FileService{

	public ModelAndView streamFile(HttpServletRequest req, HttpServletResponse res,String fileRootDir) {

		View view=null;
		
		try
		{
			String fileId=req.getParameter(CommonConstant.REQ_PARAM_FILE_ID);
			
			String fileUrl=fileRootDir+File.separator+fileId;
			
			view=new StreamView(fileUrl);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			view=new RedirectView();
		}
		
		return new ModelAndView(view);
	}
	
	public File uploadFile(UploadedFile uploadedFile,String fileRootDir,String filename)throws BaseException{
		File file =null;
		try{
			
			InputStream inputStream = uploadedFile.getInputStream();
			String serverPathFilename = fileRootDir+File.separator+filename;
			
			file=uploadFile(inputStream,serverPathFilename);
		}catch(Exception e){
			e.printStackTrace();
			throw new FileServiceException(SpringUtils.getMessage("error.file.upload",new Object[]{}));
		}
		return file;
	}
	
	public void removeFile(String fileRootDir,String filename)throws BaseException{
		try{
			String serverPathFilename = fileRootDir+File.separator+filename;
			File file = new File(serverPathFilename);
			if (file.exists())
				file.delete();
		}catch(Exception e){
			e.printStackTrace();
			throw new FileServiceException(SpringUtils.getMessage("error.remove.file",new Object[]{}));
		}
	}
	
	private File uploadFile(InputStream inputStream,String filename)throws BaseException{
		File file=null;
		try{
			file=new File(filename );
			
			if (file.exists())
				file.delete();
			
	        OutputStream out = new FileOutputStream(file);
	        
	        byte[] buf = new byte[1024];
	        int len;
	        while ((len = inputStream.read(buf)) > 0) {
	            out.write(buf, 0, len);
	        }
	        inputStream.close();
	        out.close();	
		}catch(Exception e){
			e.printStackTrace();
			throw new FileServiceException(SpringUtils.getMessage("error.file.upload",new Object[]{}));
		}
		return file;
	}
}
